package com.example.app3;  // 必须添加：声明当前类所在的包

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;

public class SecondActivity4 extends AppCompatActivity {

    private TextView tvTime;
    private long startTime = 0L;
    private long timeInMilliseconds = 0L;
    private long timeSwapBuff = 0L;
    private long updatedTime = 0L;
    private boolean isRunning = false;

    private Handler handler = new Handler();
    private Runnable updateTimerThread = new Runnable() {
        public void run() {
            // 计算当前已流逝时间
            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
            updatedTime = timeSwapBuff + timeInMilliseconds;

            // 解析为分、秒、毫秒
            int seconds = (int) (updatedTime / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            int milliseconds = (int) (updatedTime % 1000);

            // 格式化显示（两位分钟、两位秒、三位毫秒）
            tvTime.setText(String.format("%02d:%02d:%03d", minutes, seconds, milliseconds));
            handler.postDelayed(this, 0);  // 立即再次执行，保证计时流畅
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second4);  // 确保布局文件存在

        tvTime = findViewById(R.id.tv_time);  // 布局中需有id为tv_time的TextView

        // 横竖屏切换时恢复状态（核心逻辑）
        if (savedInstanceState != null) {
            startTime = savedInstanceState.getLong("startTime");
            timeSwapBuff = savedInstanceState.getLong("timeSwapBuff");
            isRunning = savedInstanceState.getBoolean("isRunning");

            if (isRunning) {
                // 恢复运行状态：重新计算开始时间
                startTime = SystemClock.uptimeMillis() - savedInstanceState.getLong("elapsedTime");
                handler.postDelayed(updateTimerThread, 0);  // 继续计时
            } else {
                // 恢复暂停状态：直接显示已保存的时间
                updatedTime = savedInstanceState.getLong("elapsedTime");
                updateTimeDisplay();
            }
        }

        // 开始按钮（使用lambda，若报错可改为匿名内部类）
        findViewById(R.id.btn_start).setOnClickListener(v -> {
            if (!isRunning) {
                startTime = SystemClock.uptimeMillis() - timeInMilliseconds;  // 从上次暂停处继续
                handler.postDelayed(updateTimerThread, 0);
                isRunning = true;
            }
        });

        // 暂停按钮
        findViewById(R.id.btn_pause).setOnClickListener(v -> {
            timeSwapBuff += timeInMilliseconds;  // 保存当前已计时长
            handler.removeCallbacks(updateTimerThread);  // 停止计时
            isRunning = false;
        });

        // 重置按钮
        findViewById(R.id.btn_reset).setOnClickListener(v -> {
            // 重置所有计时变量
            startTime = 0L;
            timeInMilliseconds = 0L;
            timeSwapBuff = 0L;
            updatedTime = 0L;
            tvTime.setText("00:00:000");  // 重置显示
            handler.removeCallbacks(updateTimerThread);  // 停止计时
            isRunning = false;
        });
    }

    // 更新时间显示（抽离为方法，避免重复代码）
    private void updateTimeDisplay() {
        int seconds = (int) (updatedTime / 1000);
        int minutes = seconds / 60;
        seconds = seconds % 60;
        int milliseconds = (int) (updatedTime % 1000);
        tvTime.setText(String.format("%02d:%02d:%03d", minutes, seconds, milliseconds));
    }

    // 保存状态到Bundle（横竖屏切换时调用）
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong("startTime", startTime);
        outState.putLong("timeSwapBuff", timeSwapBuff);
        outState.putBoolean("isRunning", isRunning);
        outState.putLong("elapsedTime", updatedTime);  // 保存当前已计时长
    }

    // 页面暂停时：若正在计时，先保存状态并停止计时
    @Override
    protected void onPause() {
        super.onPause();
        if (isRunning) {
            timeSwapBuff += timeInMilliseconds;
            handler.removeCallbacks(updateTimerThread);
        }
    }

    // 页面恢复时：若之前在计时，继续计时
    @Override
    protected void onResume() {
        super.onResume();
        if (isRunning) {
            startTime = SystemClock.uptimeMillis() - timeInMilliseconds;
            handler.postDelayed(updateTimerThread, 0);
        }
    }
}